import { useEffect, useState, useRef } from "react"

const getRandomInt = (min: number, max: number) => {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

const useLoadText = (text: string, options?: {
    spitNum?: [number, number];
    interval?: number;
    loading?: boolean;
}, effect?: {
    onEnd?: (loading: boolean) => void;
    onLoad?: () => void;
    onStart?: (loading: boolean) => void;
}) => {
    const optionsLoad = useRef<boolean>(true);
    const showRef = useRef<string>('');
    const [showText, setShowText] = useState<string>('')
    useEffect(() => {
        optionsLoad.current = options && options.loading === true ? true : false
    }, [])
    useEffect(() => {
        const startRandom = options?.spitNum ? options.spitNum[0] : 1
        const endRandom = options?.spitNum ? options.spitNum[1] : 10
        if (options === undefined || options.loading === undefined || options.loading === true) {
            const initSliceNum = getRandomInt(startRandom, endRandom)
            showRef.current += text.slice(showRef.current.length, initSliceNum)
            setShowText(showRef.current)
            const intervalTime = options?.interval || 150
            const interHanlder = setInterval(() => {
                const sliceNum = getRandomInt(startRandom, endRandom)
                const sliceText = text.slice(showRef.current.length, showRef.current.length + sliceNum)
                if (sliceText) {
                    showRef.current += sliceText
                    setShowText(showRef.current)
                    if (effect?.onLoad) effect.onLoad()
                } else {
                    clearInterval(interHanlder)
                    if (effect?.onEnd) effect.onEnd(optionsLoad.current)
                }
            }, intervalTime)
        } else {
            setShowText(text)
            if (effect?.onEnd) effect.onEnd(optionsLoad.current)
        }
    }, [text])
    return { showText, text }
};

export default useLoadText